import { asyncRouterMap, constantRouterMap, homeRouterMap } from '@/router';
import { hasPermission } from '@/utils';
import ComApi from '@/api/common';

const permission = {
  state: {
    routers: constantRouterMap,
    asyncRouters: [],
    homeRouters: []
  },
  mutations: {
    SET_ROUTERS: (state, homeRouters, asyncRouters) => {
      state.homeRouters = homeRouters;
      state.asyncRouters = asyncRouters;
      state.routers = constantRouterMap.concat(homeRouters).concat(asyncRouters);
    }
  },
  actions: {
    generateRoutes({ commit }, data) {
      return new Promise((resolve, reject) => {
        const { roles } = data;
        // OTHER ROUTE
        const asyncRouters = asyncRouterMap.filter((route) => {
          if (hasPermission(roles, route)) {
            return route;
          }
          return false;
        });
        // HOME ROUTE
        let homeRouters = [];
        ComApi.getRoutes({ name: 'home' }).then((result) => {
          if (!result.status) {
            // 添加HOME MENU角色列表
            const menus = result.obj;
            const menuKeys = [];
            for (const item of menus) {
              menuKeys.push(item.name);
              for (const route of homeRouterMap) {
                if (route.name === item.name) {
                  route.roles = item.roles;
                }
              }
            }
            // 决定是否显隐
            homeRouters = homeRouterMap.filter((route) => {
              if (hasPermission(roles, route) && (menuKeys.indexOf(route.name) >= 0)) {
                return route;
              }
              return false;
            });
            commit('SET_ROUTERS', homeRouters, asyncRouters);
            resolve({ homeRouters, asyncRouters });
          } else {
            reject();
          }
        }).catch(error => reject(error));
      });
    }
  }
};

export default permission;
